package com.example.yuanqin.page.main

import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.ConfigurationCompat
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.*
import androidx.navigation.navigation
import com.example.yuanqin.R


@Preview
@Composable
fun MainScreenPre(){
//    MaterialTheme() {
        val tabs = remember { MainSections.values() }
        val navController = rememberNavController()
//        Scaffold(
//            bottomBar = {
//                mainPageBottomBar(navController = navController,
//                    tabs = tabs)
//            },
//            modifier = Modifier.fillMaxWidth()
//                .fillMaxHeight()
//        ) {
//            MainPageScreen(
//                navController = navController,
//            )
//        }
//    }
    mainPageBottomBar(navController = navController,
                    tabs = tabs)
}


enum class MainSections(
    @StringRes val title: Int,
    val icon: ImageVector,
    val route: String
) {
    FEED(R.string.tab_home, Icons.Outlined.Home, "home/feed"),
    SEARCH(R.string.tab_message, Icons.Outlined.Search, "message/search"),
    CART(R.string.tab_mine, Icons.Outlined.ShoppingCart, "home/cart"),
}


@Composable
fun mainPageBottomBar(navController: NavHostController, tabs: Array<MainSections>) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route

    val sections = remember { MainSections.values() }
    val routes = remember { sections.map { it.route } }


    Column(
        modifier = Modifier
            .background(color = Color.White)
            .fillMaxWidth()) {
        BottomItem("Home",R.mipmap.homex)
        BottomItem("Message", R.mipmap.messgae)
        BottomItem("My", R.mipmap.my)
    }
//    Row(modifier = Modifier
//        .fillMaxWidth()
//        .height(50.dp)
//        .background(color = Color.White),
//
//    ){
//
//    }
//    if (currentRoute in routes) {
//        val currentSection = sections.first { it.route == currentRoute }
//
//        // TODO 切换动画
//        BottomBarLayout(){
//            tabs.forEach { section ->
//                val selected = section == currentSection
//                BottomNavigationItem(
//                    icon = {
//                        Icon(
//                            imageVector = section.icon,
//                            contentDescription = null
//                        )
//                    },
//                    text = {
//                        Text(
//                            text = stringResource(section.title).uppercase(
//                                ConfigurationCompat.getLocales(
//                                    LocalConfiguration.current
//                                ).get(0)
//                            ),
//                            style = MaterialTheme.typography.button,
//                            maxLines = 1
//                        )
//                    },
//                    selected = selected,
//                    onSelected = {
//                        if (section.route != currentRoute) {
//                            navController.navigate(section.route) {
//                                launchSingleTop = true
//                                restoreState = true
//                            }
//                        }
//                    },
//                    modifier = BottomNavigationItemPadding
//                        .clip(BottomNavIndicatorShape)
//                )
//            }
//        }
//
//
//
//    }
}

@Composable
fun BottomItem(text: String, @DrawableRes icon: Int){
    Column(
        modifier = Modifier
            .fillMaxHeight()
            .width(IntrinsicSize.Max),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(painter = painterResource(id = icon),
            contentDescription = null)
        Text(text = text,
            fontSize = 13.sp,
            color = Color.Black,
            modifier = Modifier
                .weight(1f)
        )
    }
}

private val TextIconSpacing = 2.dp
private val BottomNavHeight = 56.dp
private val BottomNavLabelTransformOrigin = TransformOrigin(0f, 0.5f)
private val BottomNavIndicatorShape = RoundedCornerShape(percent = 50)
private val BottomNavigationItemPadding = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)


@Composable
fun BottomBarLayout(content:@Composable () -> Unit) {
    content()
    Box(Modifier.layoutId("indicator"), content = {Spacer(
        modifier = Modifier
            .fillMaxSize()
            .then(BottomNavigationItemPadding)
    )})

}


@Composable
fun BottomNavigationItem(
    icon: @Composable BoxScope.() -> Unit,
    text: @Composable BoxScope.() -> Unit,
    selected: Boolean,
    onSelected: () -> Unit,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier.selectable(selected = selected, onClick = onSelected),
        contentAlignment = Alignment.Center
    ) {
        // Animate the icon/text positions within the item based on selection
        Box(
            modifier = Modifier
                .layoutId("icon")
                .padding(horizontal = TextIconSpacing),
            content = icon
        )
        Box(
            modifier = Modifier
                .layoutId("text")
                .padding(horizontal = TextIconSpacing)
                .graphicsLayer {
                    transformOrigin = BottomNavLabelTransformOrigin
                },
            content = text
        )
    }
}


@Composable
fun MainPageScreen(navController: NavHostController) {
    NavHost(navController = navController,
        startDestination = MainDestinations.HOME_ROUTE
    ){
        navigation(
            route = MainDestinations.HOME_ROUTE,
            startDestination = MainSections.FEED.route
        ) {
            addHomeGraph(
                onSnackSelected = { snackId: Long, from: NavBackStackEntry ->
                    // In order to discard duplicated navigation events, we check the Lifecycle
                    if (from.lifecycleIsResumed()) {
                        navController.navigate("${MainDestinations.SNACK_DETAIL_ROUTE}/$snackId")
                    }
                },
            )
        }
//        composable(
//            "${MainDestinations.SNACK_DETAIL_ROUTE}/{$SNACK_ID_KEY}",
//            arguments = listOf(navArgument(SNACK_ID_KEY) { type = NavType.LongType })
//        ) { backStackEntry ->
//            val arguments = requireNotNull(backStackEntry.arguments)
//            val snackId = arguments.getLong(SNACK_ID_KEY)
//            SnackDetail(
//                snackId = snackId,
//                upPress = {
//                    navController.navigateUp()
//                }
//            )
//        }
    }
}

private fun NavBackStackEntry.lifecycleIsResumed() =
    this.lifecycle.currentState == Lifecycle.State.RESUMED
